import { 
  Controller, 
  Post, 
  Get, 
  Put,
  Delete,
  Body, 
  Query, 
  Param, 
  Headers,
  Req,
  Res,
  UseInterceptors,
  UploadedFile,
  HttpException,
  HttpStatus,
  Logger
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { ApiTags, ApiOperation, ApiResponse, ApiHeader, ApiConsumes } from '@nestjs/swagger';
import { Request, Response } from 'express';
import { AnthropicProxyService } from './anthropic-proxy.service';
import { CopilotRequestLoggerService } from './services/copilot-request-logger.service';

// Messages DTOs
import { 
  CreateMessageDto, 
  CountTokensDto,
  MessageResponseDto,
  CountTokensResponseDto,
  MessagesQueryDto,
  AnthropicExtendedHeaders
} from './dto/messages.dto';

// Models DTOs
import { 
  ListModelsQueryDto,
  ModelsResponseDto,
  ModelDto,
  GetModelParamsDto
} from './dto/models.dto';

// Batches DTOs
import {
  CreateBatchDto,
  BatchResponseDto,
  ListBatchesQueryDto,
  BatchesResponseDto,
  GetBatchParamsDto,
  CancelBatchParamsDto
} from './dto/batches.dto';

// Files DTOs
import {
  UploadFileDto,
  FileResponseDto,
  ListFilesQueryDto,
  FilesResponseDto,
  GetFileParamsDto,
  DeleteFileParamsDto,
  DeleteFileResponseDto
} from './dto/files.dto';

import { AnthropicErrorResponseDto } from './dto/error.dto';
import { mockErrorResponses } from './mock-data/anthropic-mock.data';

@ApiTags('Anthropic API Proxy')
@Controller('v1')
@ApiHeader({
  name: 'x-api-key',
  description: 'Anthropic API Key',
  required: true
})
@ApiHeader({
  name: 'anthropic-version',
  description: 'API version (2023-06-01)',
  required: true
})
export class AnthropicProxyController {
  private readonly logger = new Logger(AnthropicProxyController.name);

  constructor(
    private readonly anthropicProxyService: AnthropicProxyService,
    private readonly copilotLogger: CopilotRequestLoggerService
  ) {}

  // ========== Messages API ========== //

  @Post('messages')
  @ApiOperation({ 
    summary: 'Create Message',
    description: 'Send a structured list of input messages with text and/or image content, and the model will generate the next message in the conversation.'
  })
  @ApiResponse({ 
    status: 201, 
    description: 'Message created successfully',
    type: MessageResponseDto
  })
  @ApiResponse({ 
    status: 400, 
    description: 'Invalid request',
    type: AnthropicErrorResponseDto
  })
  @ApiResponse({ 
    status: 401, 
    description: 'Authentication failed',
    type: AnthropicErrorResponseDto
  })
  async createMessage(
    @Body() createMessageDto: CreateMessageDto,
    @Query() query: MessagesQueryDto,
    @Headers() headers: AnthropicExtendedHeaders,
    @Req() req: Request,
    @Res() res: Response
  ): Promise<void> {
    try {
      this.logger.debug(`Processing createMessage request from IP: ${req.ip}`);
      this.logger.debug(`Request URL: ${req.method} ${req.originalUrl}`);
      this.logger.debug(`Query parameters:`, JSON.stringify(query));
      
      this.validateAnthropicHeaders(headers);
      
      // TODO: Process beta query parameter
      if (query.beta) {
        this.logger.debug('Beta parameter detected:', query.beta);
        // TODO: Enable beta features based on query parameter
      }
      
      // TODO: Process anthropic-beta header for specific beta features
      if (headers['anthropic-beta']) {
        this.logger.debug('Anthropic-beta header detected:', headers['anthropic-beta']);
        // TODO: Handle specific beta feature: fine-grained-tool-streaming-2025-05-14
      }
      
      // TODO: Process anthropic-dangerous-direct-browser-access header
      if (headers['anthropic-dangerous-direct-browser-access']) {
        this.logger.debug('Dangerous direct browser access header detected');
        // TODO: Handle direct browser access permission
      }
      
      // TODO: Forward X-Stainless-* headers to preserve client context
      const stainlessHeaders = this.extractStainlessHeaders(headers);
      this.logger.debug('Extracted stainless headers:', JSON.stringify(Object.keys(stainlessHeaders)));
      
      // TODO: Process x-app header for application context
      if (headers['x-app']) {
        this.logger.debug('X-app header detected:', headers['x-app']);
        // TODO: Handle application-specific logic (cli, web, etc.)
      }
      
      // 创建统一的请求ID用于整个请求链路追踪
      const sharedRequestId = this.copilotLogger.createRequestContext();
      
      const requestInfo = {
        headers,
        ip: req.ip,
        userAgent: req.get('User-Agent'),
        query: query ? { beta: query.beta?.toString() } : undefined, // Convert to plain object
        stainlessHeaders, // Include extracted Stainless headers
        requestId: sharedRequestId // 传递统一的请求ID
      };

      this.logger.debug('Calling anthropicProxyService.createMessage');
      const result = await this.anthropicProxyService.createMessage(createMessageDto, requestInfo);
      this.logger.debug('Controller received response from service:', JSON.stringify(result, null, 2));
      
      // 设置标准Anthropic API响应头
      this.setAnthropicResponseHeaders(res, result);
      
      // 记录响应头设置到copilot日志
      await this.copilotLogger.logCopilotRequestLegacyFormat({
        requestId: sharedRequestId,
        phase: 'completed',
        service: 'AnthropicProxyController',
        level: 'info',
        message: 'Set standard Anthropic API response headers for copilot forwarding',
        data: {
          responseHeaders: {
            'Request-Id': result.id,
            'Anthropic-Organization-Id': 'copilot-proxy-service',
            'Content-Type': 'application/json',
            'Anthropic-Ratelimit-Unified-Status': 'allowed'
          },
          responseSize: JSON.stringify(result).length,
          responseId: result.id,
          model: result.model,
          originalRequestIP: req.ip
        }
      });
      
      res.status(200).json(result);
    } catch (error) {
      this.logger.error('Error in createMessage:', error.message);
      this.logger.error('Error stack:', error.stack);
      this.handleError(error);
    }
  }

  @Post('messages/count-tokens')
  @ApiOperation({ 
    summary: 'Count Message Tokens',
    description: 'Count the number of tokens in a message request for cost estimation.'
  })
  @ApiResponse({ 
    status: 200, 
    description: 'Token count returned successfully',
    type: CountTokensResponseDto
  })
  async countTokens(
    @Body() countTokensDto: CountTokensDto,
    @Query() query: MessagesQueryDto,
    @Headers() headers: AnthropicExtendedHeaders,
    @Req() req: Request
  ): Promise<CountTokensResponseDto> {
    try {
      this.validateAnthropicHeaders(headers);
      
      // TODO: Process beta query parameter for count-tokens
      if (query.beta) {
        // TODO: Enable beta features for token counting
      }
      
      // TODO: Process extended headers for count-tokens endpoint
      const stainlessHeaders = this.extractStainlessHeaders(headers);
      
      const requestInfo = {
        headers,
        ip: req.ip,
        userAgent: req.get('User-Agent'),
        query: query ? { beta: query.beta?.toString() } : undefined, // Convert to plain object
        stainlessHeaders // Include Stainless headers
      };

      return await this.anthropicProxyService.countTokens(countTokensDto, requestInfo);
    } catch (error) {
      this.handleError(error);
    }
  }

  // ========== Models API ========== //

  @Get('models')
  @ApiOperation({ 
    summary: 'List Models',
    description: 'Get a list of available models for use with the Anthropic API.'
  })
  @ApiResponse({ 
    status: 200, 
    description: 'Models listed successfully',
    type: ModelsResponseDto
  })
  async listModels(
    @Query() query: ListModelsQueryDto,
    @Headers() headers: Record<string, string>,
    @Req() req: Request
  ): Promise<ModelsResponseDto> {
    try {
      this.validateAnthropicHeaders(headers);
      
      const requestInfo = {
        headers,
        ip: req.ip,
        userAgent: req.get('User-Agent')
      };

      return await this.anthropicProxyService.listModels(query, requestInfo);
    } catch (error) {
      this.handleError(error);
    }
  }

  @Get('models/:model_id')
  @ApiOperation({ 
    summary: 'Get Model',
    description: 'Get a specific model by ID or resolve a model alias to a model ID.'
  })
  @ApiResponse({ 
    status: 200, 
    description: 'Model retrieved successfully',
    type: ModelDto
  })
  @ApiResponse({ 
    status: 404, 
    description: 'Model not found',
    type: AnthropicErrorResponseDto
  })
  async getModel(
    @Param() params: GetModelParamsDto,
    @Headers() headers: Record<string, string>,
    @Req() req: Request
  ): Promise<ModelDto> {
    try {
      this.validateAnthropicHeaders(headers);
      
      const requestInfo = {
        headers,
        ip: req.ip,
        userAgent: req.get('User-Agent')
      };

      return await this.anthropicProxyService.getModel(params.model_id, requestInfo);
    } catch (error) {
      if (error.message.includes('not found')) {
        throw new HttpException(mockErrorResponses.notFoundError, HttpStatus.NOT_FOUND);
      }
      this.handleError(error);
    }
  }

  // ========== Message Batches API ========== //

  @Post('messages/batches')
  @ApiOperation({ 
    summary: 'Create Message Batch',
    description: 'Submit a large number of message requests to be processed asynchronously.'
  })
  @ApiResponse({ 
    status: 201, 
    description: 'Batch created successfully',
    type: BatchResponseDto
  })
  async createBatch(
    @Body() createBatchDto: CreateBatchDto,
    @Headers() headers: Record<string, string>,
    @Req() req: Request
  ): Promise<BatchResponseDto> {
    try {
      this.validateAnthropicHeaders(headers);
      
      const requestInfo = {
        headers,
        ip: req.ip,
        userAgent: req.get('User-Agent')
      };

      return await this.anthropicProxyService.createBatch(createBatchDto, requestInfo);
    } catch (error) {
      this.handleError(error);
    }
  }

  @Get('messages/batches/:message_batch_id')
  @ApiOperation({ 
    summary: 'Get Message Batch',
    description: 'Retrieve the status and details of a message batch.'
  })
  @ApiResponse({ 
    status: 200, 
    description: 'Batch retrieved successfully',
    type: BatchResponseDto
  })
  async getBatch(
    @Param() params: GetBatchParamsDto,
    @Headers() headers: Record<string, string>,
    @Req() req: Request
  ): Promise<BatchResponseDto> {
    try {
      this.validateAnthropicHeaders(headers);
      
      const requestInfo = {
        headers,
        ip: req.ip,
        userAgent: req.get('User-Agent')
      };

      return await this.anthropicProxyService.getBatch(params.message_batch_id, requestInfo);
    } catch (error) {
      this.handleError(error);
    }
  }

  @Get('messages/batches')
  @ApiOperation({ 
    summary: 'List Message Batches',
    description: 'Get a list of message batches.'
  })
  @ApiResponse({ 
    status: 200, 
    description: 'Batches listed successfully',
    type: BatchesResponseDto
  })
  async listBatches(
    @Query() query: ListBatchesQueryDto,
    @Headers() headers: Record<string, string>,
    @Req() req: Request
  ): Promise<BatchesResponseDto> {
    try {
      this.validateAnthropicHeaders(headers);
      
      const requestInfo = {
        headers,
        ip: req.ip,
        userAgent: req.get('User-Agent')
      };

      return await this.anthropicProxyService.listBatches(query, requestInfo);
    } catch (error) {
      this.handleError(error);
    }
  }

  @Post('messages/batches/:message_batch_id/cancel')
  @ApiOperation({ 
    summary: 'Cancel Message Batch',
    description: 'Cancel a message batch that is currently processing.'
  })
  @ApiResponse({ 
    status: 200, 
    description: 'Batch cancelled successfully',
    type: BatchResponseDto
  })
  async cancelBatch(
    @Param() params: CancelBatchParamsDto,
    @Headers() headers: Record<string, string>,
    @Req() req: Request
  ): Promise<BatchResponseDto> {
    try {
      this.validateAnthropicHeaders(headers);
      
      const requestInfo = {
        headers,
        ip: req.ip,
        userAgent: req.get('User-Agent')
      };

      return await this.anthropicProxyService.cancelBatch(params.message_batch_id, requestInfo);
    } catch (error) {
      this.handleError(error);
    }
  }

  // ========== Files API ========== //

  @Post('files')
  @ApiOperation({ 
    summary: 'Upload File',
    description: 'Upload a file that can be used with other API endpoints.'
  })
  @ApiConsumes('multipart/form-data')
  @UseInterceptors(FileInterceptor('file'))
  @ApiResponse({ 
    status: 201, 
    description: 'File uploaded successfully',
    type: FileResponseDto
  })
  async uploadFile(
    @UploadedFile() file: Express.Multer.File,
    @Body('purpose') purpose: string,
    @Headers() headers: Record<string, string>,
    @Req() req: Request
  ): Promise<FileResponseDto> {
    try {
      this.validateAnthropicHeaders(headers);
      
      if (!file) {
        throw new HttpException(
          { type: 'error', error: { type: 'invalid_request_error', message: 'No file provided' } },
          HttpStatus.BAD_REQUEST
        );
      }

      const requestInfo = {
        headers,
        ip: req.ip,
        userAgent: req.get('User-Agent')
      };

      return await this.anthropicProxyService.uploadFile(file, purpose, requestInfo);
    } catch (error) {
      this.handleError(error);
    }
  }

  @Get('files')
  @ApiOperation({ 
    summary: 'List Files',
    description: 'Get a list of uploaded files.'
  })
  @ApiResponse({ 
    status: 200, 
    description: 'Files listed successfully',
    type: FilesResponseDto
  })
  async listFiles(
    @Query() query: ListFilesQueryDto,
    @Headers() headers: Record<string, string>,
    @Req() req: Request
  ): Promise<FilesResponseDto> {
    try {
      this.validateAnthropicHeaders(headers);
      
      const requestInfo = {
        headers,
        ip: req.ip,
        userAgent: req.get('User-Agent')
      };

      return await this.anthropicProxyService.listFiles(query, requestInfo);
    } catch (error) {
      this.handleError(error);
    }
  }

  @Get('files/:file_id')
  @ApiOperation({ 
    summary: 'Get File',
    description: 'Retrieve metadata for a specific file.'
  })
  @ApiResponse({ 
    status: 200, 
    description: 'File retrieved successfully',
    type: FileResponseDto
  })
  async getFile(
    @Param() params: GetFileParamsDto,
    @Headers() headers: Record<string, string>,
    @Req() req: Request
  ): Promise<FileResponseDto> {
    try {
      this.validateAnthropicHeaders(headers);
      
      const requestInfo = {
        headers,
        ip: req.ip,
        userAgent: req.get('User-Agent')
      };

      return await this.anthropicProxyService.getFile(params.file_id, requestInfo);
    } catch (error) {
      if (error.message.includes('not found')) {
        throw new HttpException(mockErrorResponses.notFoundError, HttpStatus.NOT_FOUND);
      }
      this.handleError(error);
    }
  }

  @Get('files/:file_id/content')
  @ApiOperation({ 
    summary: 'Get File Content',
    description: 'Download the content of a specific file.'
  })
  @ApiResponse({ 
    status: 200, 
    description: 'File content retrieved successfully'
  })
  async getFileContent(
    @Param() params: GetFileParamsDto,
    @Headers() headers: Record<string, string>,
    @Req() req: Request,
    @Res() res: Response
  ): Promise<void> {
    try {
      this.validateAnthropicHeaders(headers);
      
      const requestInfo = {
        headers,
        ip: req.ip,
        userAgent: req.get('User-Agent')
      };

      const content = await this.anthropicProxyService.getFileContent(params.file_id, requestInfo);
      
      res.setHeader('Content-Type', 'application/octet-stream');
      res.setHeader('Content-Disposition', `attachment; filename="${params.file_id}.data"`);
      res.send(content);
    } catch (error) {
      if (error.message.includes('not found')) {
        throw new HttpException(mockErrorResponses.notFoundError, HttpStatus.NOT_FOUND);
      }
      this.handleError(error);
    }
  }

  @Delete('files/:file_id')
  @ApiOperation({ 
    summary: 'Delete File',
    description: 'Delete a previously uploaded file.'
  })
  @ApiResponse({ 
    status: 200, 
    description: 'File deleted successfully',
    type: DeleteFileResponseDto
  })
  async deleteFile(
    @Param() params: DeleteFileParamsDto,
    @Headers() headers: Record<string, string>,
    @Req() req: Request
  ): Promise<DeleteFileResponseDto> {
    try {
      this.validateAnthropicHeaders(headers);
      
      const requestInfo = {
        headers,
        ip: req.ip,
        userAgent: req.get('User-Agent')
      };

      return await this.anthropicProxyService.deleteFile(params.file_id, requestInfo);
    } catch (error) {
      this.handleError(error);
    }
  }

  // ========== Debug/Monitoring Endpoints ========== //

  @Get('proxy/logs')
  @ApiOperation({ 
    summary: 'Get Request Logs',
    description: 'Retrieve recent request logs for debugging and monitoring (Development only).'
  })
  async getRequestLogs(@Query('limit') limit?: number) {
    const logs = this.anthropicProxyService.getRequestLogs(limit ? parseInt(limit.toString()) : 100);
    return { logs, total: logs.length };
  }

  @Post('proxy/logs/clear')
  @ApiOperation({ 
    summary: 'Clear Request Logs',
    description: 'Clear all stored request logs (Development only).'
  })
  async clearRequestLogs() {
    this.anthropicProxyService.clearRequestLogs();
    return { message: 'Request logs cleared successfully' };
  }

  @Get('proxy/config/full')
  @ApiOperation({ 
    summary: 'Get Full Proxy Configuration',
    description: 'Get complete proxy configuration including Copilot settings.'
  })
  async getFullProxyConfig() {
    return this.anthropicProxyService.getFullProxyConfig();
  }

  @Put('proxy/config/copilot')
  @ApiOperation({ 
    summary: 'Update Copilot Configuration',
    description: 'Update Copilot-specific configuration settings.'
  })
  async updateCopilotConfig(@Body() updateDto: any) {
    return this.anthropicProxyService.updateCopilotConfig(updateDto);
  }

  @Post('proxy/config/test-connection')
  @ApiOperation({ 
    summary: 'Test Copilot Connection',
    description: 'Test connection to Copilot API with provided token.'
  })
  async testCopilotConnection(@Body() testDto: any) {
    return this.anthropicProxyService.testCopilotConnection(testDto);
  }

  @Get('proxy/config/token-info')
  @ApiOperation({ 
    summary: 'Get Token Information',
    description: 'Get information about the current Copilot token.'
  })
  async getTokenInfo() {
    return this.anthropicProxyService.getTokenInfo();
  }

  @Post('proxy/config/mode')
  @ApiOperation({ 
    summary: 'Switch Proxy Mode',
    description: 'Switch between Mock and Copilot proxy modes.'
  })
  async switchMode(@Body() switchDto: any) {
    return this.anthropicProxyService.switchMode(switchDto.mode);
  }

  @Post('proxy/config/refresh-token')
  @ApiOperation({ 
    summary: 'Refresh Copilot Token',
    description: 'Manually refresh the Copilot token using the configured GitHub token.'
  })
  async refreshToken() {
    return this.anthropicProxyService.refreshToken();
  }

  @Get('proxy/config/token-health')
  @ApiOperation({ 
    summary: 'Get Token Health Status',
    description: 'Get detailed token health status including expiry and validity information.'
  })
  async getTokenHealth() {
    return this.anthropicProxyService.getTokenHealth();
  }

  @Get('proxy/logs/copilot-files')
  @ApiOperation({ 
    summary: 'Get Copilot Request Log Files',
    description: 'Get a list of available Copilot request log files.'
  })
  async getCopilotLogFiles() {
    try {
      // 新的日志系统使用数据库，不再有文件列表
      const files = [];
      return {
        success: true,
        files,
        total: files.length
      };
    } catch (error) {
      this.logger.error(`Failed to get log files: ${error.message}`);
      return {
        success: false,
        error: error.message,
        files: []
      };
    }
  }

  @Get('proxy/logs/copilot/:filename')
  @ApiOperation({ 
    summary: 'Get Copilot Request Log Content',
    description: 'Get the content of a specific Copilot request log file.'
  })
  async getCopilotLogContent(
    @Param('filename') filename: string,
    @Query('lines') lines?: string
  ) {
    try {
      const lineLimit = lines ? parseInt(lines) : undefined;
      // 新的日志系统使用数据库，不再支持文件读取
      const content = 'Log file reading is not supported in the new database-based logging system. Please use the /copilot-logs API endpoints to view logs.';
      return {
        success: true,
        filename,
        content,
        lines: content.split('\n').length
      };
    } catch (error) {
      this.logger.error(`Failed to read log file ${filename}: ${error.message}`);
      return {
        success: false,
        error: error.message,
        filename
      };
    }
  }

  // ========== Private Helper Methods ========== //

  private validateAnthropicHeaders(headers: Record<string, string>): void {
    // 记录收到的头部信息用于调试
    this.logger.debug('Received headers:', JSON.stringify(Object.keys(headers)));
    
    const apiKey = headers['x-api-key'];
    const version = headers['anthropic-version'];

    // 只记录 API key 状态，不进行强制校验
    if (!apiKey) {
      this.logger.log('No x-api-key header provided in request');
    } else {
      this.logger.log(`API Key provided: ${this.maskApiKey(apiKey)}`);
    }

    // 只记录 version 状态，不进行强制校验
    if (!version) {
      this.logger.log('No anthropic-version header provided in request');
    } else {
      this.logger.log(`Anthropic version: ${version}`);
    }

    // 记录所有可用头部用于调试
    this.logger.debug('Available headers:', Object.keys(headers).join(', '));
  }

  private maskApiKey(apiKey: string): string {
    if (apiKey.length <= 8) return '***';
    return apiKey.substring(0, 4) + '***' + apiKey.substring(apiKey.length - 4);
  }

  /**
   * Extract X-Stainless-* headers for client context preservation
   * TODO: Implement forwarding logic for these headers to downstream services
   */
  private extractStainlessHeaders(headers: AnthropicExtendedHeaders): Record<string, string> {
    const stainlessHeaders: Record<string, string> = {};
    
    // Extract all X-Stainless-* headers
    const stainlessKeys = [
      'X-Stainless-Lang',
      'X-Stainless-Package-Version', 
      'X-Stainless-OS',
      'X-Stainless-Arch',
      'X-Stainless-Runtime',
      'X-Stainless-Runtime-Version',
      'X-Stainless-Retry-Count',
      'X-Stainless-Timeout',
      'x-stainless-helper-method'
    ];
    
    stainlessKeys.forEach(key => {
      if (headers[key]) {
        stainlessHeaders[key] = headers[key];
      }
    });
    
    // TODO: Add logic to forward these headers to Copilot API
    // TODO: Add validation for Stainless header values
    // TODO: Add metrics collection for client library usage
    
    return stainlessHeaders;
  }

  /**
   * 设置标准Anthropic API响应头
   */
  private setAnthropicResponseHeaders(res: Response, response: MessageResponseDto): void {
    // 基本响应头
    res.setHeader('Content-Type', 'application/json');
    
    // Anthropic特有的响应头
    res.setHeader('Request-Id', response.id);
    res.setHeader('Anthropic-Organization-Id', 'copilot-proxy-service');
    
    // 模拟Rate Limiting响应头 (基于当前时间和一些合理的默认值)
    const now = Math.floor(Date.now() / 1000);
    const resetTime = now + 3600; // 1小时后重置
    res.setHeader('Anthropic-Ratelimit-Unified-Fallback', 'available');
    res.setHeader('Anthropic-Ratelimit-Unified-Fallback-Percentage', '0.5');
    res.setHeader('Anthropic-Ratelimit-Unified-Representative-Claim', 'five_hour');
    res.setHeader('Anthropic-Ratelimit-Unified-Reset', resetTime.toString());
    res.setHeader('Anthropic-Ratelimit-Unified-Status', 'allowed');
    
    // 其他标准响应头
    res.setHeader('X-Robots-Tag', 'none');
    res.setHeader('Timing-Allow-Origin', '*');
    
    // 记录响应头设置
    this.logger.debug('Set Anthropic API compatible response headers', {
      requestId: response.id,
      rateLimitReset: resetTime
    });
  }

  private handleError(error: any): never {
    this.logger.error(`Anthropic Proxy Error: ${error.message}`);
    this.logger.error(`Error type: ${error.constructor.name}`);
    if (error.stack) {
      this.logger.error(`Error stack: ${error.stack}`);
    }
    
    // 记录错误详细信息
    if (error.response) {
      this.logger.error('Error response:', JSON.stringify(error.response));
    }
    
    if (error instanceof HttpException) {
      this.logger.error(`HttpException status: ${error.getStatus()}`);
      this.logger.error(`HttpException response:`, JSON.stringify(error.getResponse()));
      throw error;
    }

    // 记录未知错误类型
    this.logger.error('Unhandled error type, returning 500');
    
    // 默认返回内部服务器错误
    throw new HttpException(
      {
        type: 'error',
        error: {
          type: 'api_error',
          message: 'Internal server error occurred'
        }
      },
      HttpStatus.INTERNAL_SERVER_ERROR
    );
  }
}